package com.xiaojie.core;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * @ClassName MyWebApplicationInitializer
 * @Author 廖杰
 * @Date 2021/6/15 22:41
 **/
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    static int init = 0;

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        // 只需要加载一次
        init++;
        if(init > 1) {
            return;
        }
        // Load Spring web application configuration
        //通过注解的方式初始化Spring的上下文
        AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
        // 将启动类作为配置类加载
        Class configClass = (Class) servletContext.getAttribute("loadClass");
        ac.register(configClass);
        ac.refresh();

        // Create and register the DispatcherServlet
        //基于java代码的方式初始化DispatcherServlet
        DispatcherServlet servlet = new DispatcherServlet(ac);
        ServletRegistration.Dynamic registration = servletContext.addServlet("/*", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/*");

    }
}
